<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h2 class="page-title">数据概览</h2>
      <div class="dashboard-controls">
        <el-button @click="manualRefresh" :loading="chartLoading" type="primary">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stats-card">
        <div class="stats-content">
          <div class="stats-icon elderly">
            <el-icon><User /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ elderlyCount }}</h3>
            <p>老人总数</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stats-card">
        <div class="stats-content">
          <div class="stats-icon health">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ healthRecordCount }}</h3>
            <p>健康记录</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stats-card">
        <div class="stats-content">
          <div class="stats-icon appointment">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ appointmentCount }}</h3>
            <p>预约服务</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stats-card">
        <div class="stats-content">
          <div class="stats-icon staff">
            <el-icon><Avatar /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ staffCount }}</h3>
            <p>护理人员</p>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-grid">
      <!-- 健康记录趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <span>近7天健康记录趋势</span>
        </template>
        <v-chart 
          class="chart" 
          :option="healthTrendOption" 
          :loading="chartLoading"
          autoresize
        />
      </el-card>
      
      <!-- 预约趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <span>近7天预约服务趋势</span>
        </template>
        <v-chart 
          class="chart" 
          :option="appointmentTrendOption" 
          :loading="chartLoading"
          autoresize
        />
      </el-card>
      
      <!-- 健康状态分布饼图 -->
      <el-card class="chart-card">
        <template #header>
          <span>健康状态分布</span>
        </template>
        <v-chart 
          class="chart" 
          :option="healthStatusOption" 
          :loading="chartLoading"
          autoresize
        />
      </el-card>
      
      <!-- 服务类型分布饼图 -->
      <el-card class="chart-card">
        <template #header>
          <span>服务类型分布</span>
        </template>
        <v-chart 
          class="chart" 
          :option="serviceTypeOption" 
          :loading="chartLoading"
          autoresize
        />
      </el-card>
      
      <!-- 年龄分布柱状图 -->
      <el-card class="chart-card">
        <template #header>
          <span>老人年龄分布</span>
        </template>
        <v-chart 
          class="chart" 
          :option="ageDistributionOption" 
          :loading="chartLoading"
          autoresize
        />
      </el-card>
      
      <!-- 预约状态分布 -->
      <el-card class="chart-card">
        <template #header>
          <span>预约状态分布</span>
        </template>
        <v-chart 
          class="chart" 
          :option="appointmentStatusOption" 
          :loading="chartLoading"
          autoresize
        />
      </el-card>
    </div>
    
    <!-- 最近动态 -->
    <el-card class="recent-activity">
      <template #header>
        <span>最近动态</span>
        <el-button type="text" @click="loadRecentActivities" :loading="activityLoading">
          刷新
        </el-button>
      </template>
      
      <el-timeline v-if="recentActivities.length > 0">
        <el-timeline-item
          v-for="activity in recentActivities"
          :key="activity.id"
          :timestamp="activity.time"
          :type="activity.type"
        >
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
      
      <el-empty v-else description="暂无动态数据" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { User, Document, Calendar, Avatar, Refresh } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

// 统计数据
const elderlyCount = ref(0)
const healthRecordCount = ref(0)
const appointmentCount = ref(0)
const staffCount = ref(0)

// 加载状态
const chartLoading = ref(true)
const activityLoading = ref(false)

// 最近动态数据
const recentActivities = ref<any[]>([])

// 图表配置
const healthTrendOption = ref({})
const appointmentTrendOption = ref({})
const healthStatusOption = ref({})
const serviceTypeOption = ref({})
const ageDistributionOption = ref({})
const appointmentStatusOption = ref({})

// 获取认证头
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  }
}

// 加载仪表板统计数据
const loadDashboardData = async () => {
  try {
    console.log('=== 开始加载仪表板统计数据 ===')
    // 使用dashboard统计接口
    const response = await fetch(`${API_BASE_URL}/dashboard/statistics`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    console.log('统计数据响应状态:', response.status)
    
    if (response.ok) {
      const result = await response.json()
      console.log('统计数据响应结果:', result)
      
      if (result.code === 200) {
        const data = result.data
        console.log('解析的统计数据:', data)
        elderlyCount.value = data.elderlyCount || 0
        healthRecordCount.value = data.healthRecordCount || 0
        appointmentCount.value = data.appointmentCount || 0
        staffCount.value = data.staffCount || 0
        console.log('设置后的统计数据:', {
          elderlyCount: elderlyCount.value,
          healthRecordCount: healthRecordCount.value,
          appointmentCount: appointmentCount.value,
          staffCount: staffCount.value
        })
      }
    } else {
      throw new Error('获取统计数据失败')
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载健康记录趋势
const loadHealthTrend = async () => {
  try {
    console.log('=== 开始加载健康记录趋势 ===')
    const response = await fetch(`${API_BASE_URL}/dashboard/health-trend`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    console.log('健康记录趋势响应状态:', response.status)
    
    if (response.ok) {
      const result = await response.json()
      console.log('健康记录趋势响应结果:', result)
      
      if (result.code === 200 && result.data) {
        const data = result.data
        console.log('健康记录趋势数据:', data)
        healthTrendOption.value = {
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: data.dates || []
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: '健康记录数',
            type: 'line',
            data: data.counts || [],
            smooth: true,
            itemStyle: {
              color: '#f093fb'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(240, 147, 251, 0.3)' },
                  { offset: 1, color: 'rgba(240, 147, 251, 0.1)' }
                ]
              }
            }
          }]
        }
        console.log('设置健康记录趋势图表配置完成')
      } else {
        console.log('健康记录趋势API返回数据格式不正确或无数据')
      }
    } else {
      console.log('健康记录趋势API调用失败，状态码:', response.status)
    }
  } catch (error) {
    console.error('加载健康记录趋势失败:', error)
  }
}

// 加载预约趋势
const loadAppointmentTrend = async () => {
  try {
    console.log('=== 开始加载预约趋势 ===')
    const response = await fetch(`${API_BASE_URL}/dashboard/appointment-trend`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    console.log('预约趋势响应状态:', response.status)
    
    if (response.ok) {
      const result = await response.json()
      console.log('预约趋势响应结果:', result)
      
      if (result.code === 200 && result.data) {
        const data = result.data
        console.log('预约趋势数据:', data)
        appointmentTrendOption.value = {
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: data.dates || []
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: '预约数量',
            type: 'line',
            data: data.counts || [],
            smooth: true,
            itemStyle: {
              color: '#4facfe'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(79, 172, 254, 0.3)' },
                  { offset: 1, color: 'rgba(79, 172, 254, 0.1)' }
                ]
              }
            }
          }]
        }
        console.log('设置预约趋势图表配置完成')
      } else {
        console.log('预约趋势API返回数据格式不正确或无数据')
      }
    } else {
      console.log('预约趋势API调用失败，状态码:', response.status)
    }
  } catch (error) {
    console.error('加载预约趋势失败:', error)
  }
}

// 加载健康状态分布
const loadHealthStatus = async () => {
  try {
    console.log('=== 开始加载健康状态分布 ===')
    const response = await fetch(`${API_BASE_URL}/dashboard/health-status`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    console.log('健康状态分布响应状态:', response.status)
    
    if (response.ok) {
      const result = await response.json()
      console.log('健康状态分布响应结果:', result)
      
      if (result.code === 200 && result.data) {
        const data = result.data
        console.log('健康状态分布数据:', data)
        
        // 从statusStatistics中提取数据
        let seriesData: Array<{name: string, value: number}> = []
        if (data.statusStatistics) {
          const statusMap: Record<string, string> = {
            'normal': '正常',
            'high': '偏高', 
            'low': '偏低',
            'abnormal': '异常'
          }
          
          Object.keys(data.statusStatistics).forEach(key => {
            const value = data.statusStatistics[key]
            if (value > 0) {
              seriesData.push({
                name: statusMap[key] || key,
                value: value
              })
            }
          })
        }
        
        // 如果没有状态统计数据，使用类型统计数据
        if (seriesData.length === 0 && data.typeStatistics) {
          const typeMap: Record<string, string> = {
            'temperature': '体温记录',
            'heart_rate': '心率记录',
            'blood_pressure': '血压记录',
            'blood_sugar': '血糖记录',
            'weight': '体重记录'
          }
          
          Object.keys(data.typeStatistics).forEach(key => {
            const value = data.typeStatistics[key]
            if (value > 0) {
              seriesData.push({
                name: typeMap[key] || key,
                value: value
              })
            }
          })
        }
        
        console.log('处理后的健康状态数据:', seriesData)
        
        if (seriesData.length > 0) {
          healthStatusOption.value = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left'
            },
            series: [{
              name: '健康状态',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              data: seriesData,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }]
          }
          console.log('设置健康状态图表配置完成')
          return
        }
      }
    }
  } catch (error) {
    console.error('加载健康状态分布失败:', error)
  }
}

// 加载服务类型分布
const loadServiceType = async () => {
  try {
    console.log('=== 开始加载服务类型分布 ===')
    const response = await fetch(`${API_BASE_URL}/dashboard/service-type`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    console.log('服务类型分布响应状态:', response.status)
    
    if (response.ok) {
      const result = await response.json()
      console.log('服务类型分布响应结果:', result)
      
      if (result.code === 200 && result.data) {
        console.log('服务类型分布数据:', result.data)
        serviceTypeOption.value = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [{
            name: '服务类型',
            type: 'pie',
            radius: '50%',
            data: result.data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        }
        console.log('设置服务类型图表配置完成')
      }
    }
  } catch (error) {
    console.error('加载服务类型分布失败:', error)
  }
}

// 加载年龄分布
const loadAgeDistribution = async () => {
  try {
    console.log('=== 开始加载年龄分布 ===')
    const response = await fetch(`${API_BASE_URL}/dashboard/age-distribution`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    console.log('年龄分布响应状态:', response.status)
    
    if (response.ok) {
      const result = await response.json()
      console.log('年龄分布响应结果:', result)
      
      if (result.code === 200 && result.data) {
        const data = result.data
        console.log('年龄分布原始数据:', data)
        const categories = data.map((item: any) => item.name)
        const values = data.map((item: any) => item.value)
        
        console.log('年龄分布处理后数据:', { categories, values })
        
        ageDistributionOption.value = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: categories
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            name: '人数',
            type: 'bar',
            data: values,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: '#43e97b' },
                  { offset: 1, color: '#38f9d7' }
                ]
              }
            }
          }]
        }
        console.log('年龄分布图表配置设置完成')
      } else {
        console.log('年龄分布API返回数据格式不正确或无数据:', result)
      }
    } else {
      console.log('年龄分布API调用失败，状态码:', response.status)
      const errorText = await response.text()
      console.log('错误响应内容:', errorText)
    }
  } catch (error) {
    console.error('加载年龄分布失败:', error)
  }
}

// 加载预约状态分布
const loadAppointmentStatus = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/dashboard/appointment-status`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    if (response.ok) {
      const result = await response.json()
      
      if (result.code === 200 && result.data) {
        const data = result.data
        const seriesData = [
          { name: '待确认', value: data.PENDING || 0 },
          { name: '已确认', value: data.CONFIRMED || 0 },
          { name: '进行中', value: data.IN_PROGRESS || 0 },
          { name: '已完成', value: data.COMPLETED || 0 },
          { name: '已取消', value: data.CANCELLED || 0 }
        ].filter(item => item.value > 0)
        
        appointmentStatusOption.value = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            bottom: '0%',
            left: 'center'
          },
          series: [{
            name: '预约状态',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '45%'],
            data: seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        }
      }
    }
  } catch (error) {
    console.error('加载预约状态分布失败:', error)
  }
}

// 加载最近动态
const loadRecentActivities = async () => {
  activityLoading.value = true
  try {
    const response = await fetch(`${API_BASE_URL}/dashboard/recent-activities`, {
      method: 'GET',
      headers: getAuthHeaders()
    })
    
    if (response.ok) {
      const result = await response.json()
      
      if (result.code === 200 && result.data) {
        recentActivities.value = result.data.map((item: any) => ({
          id: item.id,
          content: item.content,
          time: item.createTime || item.time,
          type: item.type || 'primary'
        }))
        return
      }
    }
    
    // 使用模拟数据
    const now = new Date()
    recentActivities.value = [
      {
        id: 1,
        content: '老人张三完成了今日健康检查',
        time: new Date(now.getTime() - 10 * 60 * 1000).toLocaleString(),
        type: 'success'
      },
      {
        id: 2,
        content: '新增预约：李四预约了明日康复训练',
        time: new Date(now.getTime() - 30 * 60 * 1000).toLocaleString(),
        type: 'primary'
      },
      {
        id: 3,
        content: '健康记录更新：王五的血压数据已记录',
        time: new Date(now.getTime() - 45 * 60 * 1000).toLocaleString(),
        type: 'info'
      },
      {
        id: 4,
        content: '护理人员赵六开始了今日值班',
        time: new Date(now.getTime() - 2 * 60 * 60 * 1000).toLocaleString(),
        type: 'success'
      },
      {
        id: 5,
        content: '预约取消：老人孙七取消了下午的心理咨询',
        time: new Date(now.getTime() - 3 * 60 * 60 * 1000).toLocaleString(),
        type: 'warning'
      }
    ]
  } catch (error) {
    console.error('加载最近动态失败:', error)
  } finally {
    activityLoading.value = false
  }
}

// 加载所有数据
const loadAllData = async () => {
  chartLoading.value = true
  
  await Promise.all([
    loadDashboardData(),
    loadHealthTrend(),
    loadAppointmentTrend(),
    loadHealthStatus(),
    loadServiceType(),
    loadAgeDistribution(),
    loadAppointmentStatus(),
    loadRecentActivities()
  ])
  
  chartLoading.value = false
}

// 手动刷新
const manualRefresh = () => {
  loadAllData()
}

onMounted(() => {
  loadAllData()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.dashboard-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 500;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stats-icon.elderly {
  background: linear-gradient(45deg, #667eea, #764ba2);
}

.stats-icon.health {
  background: linear-gradient(45deg, #f093fb, #f5576c);
}

.stats-icon.appointment {
  background: linear-gradient(45deg, #4facfe, #00f2fe);
}

.stats-icon.staff {
  background: linear-gradient(45deg, #43e97b, #38f9d7);
}

.stats-info h3 {
  margin: 0 0 5px 0;
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stats-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  min-height: 300px;
}

.chart {
  width: 100%;
  height: 300px;
}

.chart-placeholder {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.recent-activity {
  margin-bottom: 20px;
}

.el-timeline {
  padding-left: 10px;
}
</style> 